package io2.bio;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class BioServer2 {
    static ExecutorService executorService = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("服务启动 8080");
        while(true) {
            final Socket socket = serverSocket.accept();
            if(socket != null) {
                executorService.execute(() -> {
                    System.out.println("新建连接：" + socket.getRemoteSocketAddress());
                    BufferedReader bufferedReader = null;
                    BufferedWriter bufferedWriter = null;
                    try {
                        bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        String str;
                        while((str = bufferedReader.readLine()) != null && str.length() != 0)
                            System.out.println("收到数据：" + str);
                        System.out.println("数据接收完毕，数据来自：" + socket.getRemoteSocketAddress());
                        bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                        bufferedWriter.write("HTTP/1.1 200 OK\r\nContent-length:13\r\n\r\nHello, World!\r\n");
                        bufferedWriter.flush();
//                    socket.getOutputStream().write("HTTP/1.1 200 OK\r\nContent-length:13\r\n\r\nHello, World!\r\n".getBytes());
//                    socket.getOutputStream().flush();
                    System.out.println("响应数据发送完毕");
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if(bufferedReader != null) {
                            try {
                                bufferedReader.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if(bufferedWriter != null) {
                            try {
                                bufferedWriter.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }
}
